<template>
  <div class="agent">

    <div class="df jc-sb title-btn">
      <div>
        <el-input v-model="search_inp" @keydown.enter="search_click" placeholder="输入任意字段进行模糊查询" class="input-with-select">
          <template #append>
            <el-button @click="search_click" :icon="Search" />
          </template>
        </el-input>
      </div>
      <el-button type="primary" @click="insert_into">代理开户</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%;margin-top: 15px;" border>
      <el-table-column prop="ManagerAgentUserName" label="上级代理" />
      <el-table-column prop="AgentLevel" label="代理层级">
        <template #default="scope">
          <span>{{ scope.row.AgentLevel==0?'最高代理':scope.row.AgentLevel==1?'一级代理':scope.row.AgentLevel==2?'二级代理':scope.row.AgentLevel==3?'三级代理': `${scope.row.AgentLevel}级代理`     }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="AgentUserName" label="用户名" />
      <el-table-column prop="AgentUserPassword" label="密码" />
      <el-table-column prop="Phone" label="手机号" />
      <el-table-column prop="LoginIP" label="登录IP" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <div>
            <el-switch v-model="scope.row.status" @change="switch_change(scope.row)" />
            <span style="margin-left: 5px;">{{scope.row.status?'开启':'关闭'}}</span>
          </div>
        </template>

      </el-table-column>

      <el-table-column prop="" label="操作" width="300">
        <template #default="scope">
          <el-button @click="edit(scope.row)" size="small" type="primary" link>修改</el-button>
          <el-popconfirm title="不在考虑一下?" confirm-button-text="确定" cancel-button-text="取消" @confirm="enter_del(scope.row)">
            <template #reference>
              <el-button size="small" type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog draggable v-model="dialogVisible" title="提示" width="40%">
      <el-form style="padding-right: 40px;" ref="ruleFormRef" :model="formData" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
        <el-form-item label="上级代理:" prop="ManagerAgentUserName">
          <!-- <el-input v-model="formData.ManagerAgentUserName" /> -->
          <el-select v-model="formData.ManagerAgentUserName" placeholder="请选择上级代理" style="width: 100%;">
            <el-option v-for="(item,index) in prev_list" :key="index" :label="item.AgentUserName" :value="item.AgentUserName" @click="select_change(item)" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名:" prop="AgentUserName">
          <el-input v-model="formData.AgentUserName" :disabled="is_add_edit=='edit'?true:false" />
        </el-form-item>
        <el-form-item label="密码:" prop="AgentUserPassword">
          <el-input v-model="formData.AgentUserPassword" />
        </el-form-item>
        <el-form-item label="手机号:" prop="Phone">
          <el-input v-model="formData.Phone" />
        </el-form-item>
        <el-form-item label="登录IP:" prop="IP">
          <el-input v-model="formData.LoginIP" />
        </el-form-item>
        <el-form-item label="状态:" prop="AgentStatus">
          <el-switch v-model="is_Status" />
          <!-- {{ is_Status }} -->
          <span style="margin-left: 5px;">{{is_Status?'开启':'关闭'}}</span>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="enter">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import http from '../../http/index'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { useCounterStore } from '../../current/index'
import { storeToRefs } from 'pinia'
import { Search } from '@element-plus/icons-vue'
const store = useCounterStore()
const { edit_table, formart_sql, delete_sql } = store //方法
const { userInfo } = storeToRefs(store) //  数据

onMounted(async () => {
  // console.log(await get_list("SELECT * FROM agentuser", "userglobal"));
  await get_list(
    'SELECT * FROM agentuser ORDER BY agentuser.AgentUserName LIMIT 15 OFFSET 0',
    'userglobal'
  )

  console.log(tableData.value)
  console.log(Object.keys(tableData.value[0]))
})
const tableData = ref([])

// 手机号检验规则
const iphone_rules = (rule: any, value: any, callback: any) => {
  console.log(rule, value, callback)

  // 校验手机号
  let reg = /^[1][3-9]\d{9}$/
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else if (reg.test(value)) {
    callback()
  } else {
    callback(new Error('请输入11位的手机号'))
  }
}
const rules = reactive<FormRules>({
  AgentUserName: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    { min: 3, max: 10, message: '长度3-10个字符', trigger: 'change' }
  ],
  AgentUserPassword: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 4, max: 18, message: '长度4-18位字符', trigger: 'change' }
  ],
  Phone: [
    { validator: iphone_rules, trigger: 'change', required: true }
    // { min: 11, max: 11, message: "长度11位数字", trigger: "blur" },
  ]
})

const formData = ref({
  AgentLevel: '', //层级
  AgentMisc: '',
  AgentNotice: '',
  AgentStatus: '', // 封禁状态
  AgentUserName: '',
  AgentUserPassword: '',
  IDCard: '',
  LoginIP: '',
  ManagerAgentUserName: null, //上级代理
  Phone: ''
})
const is_Status = ref(true)
const dialogVisible = ref(false)
const end_status = ref('')
const is_add_edit = ref('') //判断是添加还是修改
const edit = async (row) => {
  console.log(row)
  is_add_edit.value = 'edit'
  formData.value = row
  // formData.value.AgentStatus = row.status;
  is_Status.value = row.AgentStatus == '0' ? true : false
  // formData.value.AgentLevel =row.AgentLevel
  dialogVisible.value = true

  // recursion_fun(`3`, "userglobal");

  // let keys_arr = Object.keys(tableData.value[0]);
  // let keys_arr2 = Object.keys(formData.value);

  // let str = ''
  // for (var i = 0; i < keys_arr.length; i++) {
  //   // console.log(keys_arr[i]);

  //   // console.log(formData.value[keys_arr[i]]);

  //   console.log(`${keys_arr[i]}=${formData.value[keys_arr[i]]}`);

  //   // for (var j = 0; j < keys_arr2.length; j++) {
  //   //   if(keys_arr[i] = keys_arr2[i]){
  //   //     console.log(`${keys_arr[i]}=${formData.value[keys_arr[i]]}`);

  //   str = str+= `${keys_arr[i]}=${formData.value[keys_arr[i]]},`
  //   //   }
  //   // }
  // }
  // console.log(str);
}

const enter = async () => {
  formData.value.AgentStatus = is_Status.value ? '0' : '1'
  formData.value.ManagerAgentUserName =
    formData.value.ManagerAgentUserName == '' ? null : formData.value.ManagerAgentUserName
  formData.value.AgentLevel = formData.value.AgentLevel == '' ? '0' : formData.value.AgentLevel
  delete formData.value.status
  let sql_formart = await formart_sql(formData.value)
  console.log(sql_formart)
  // formData.value.ManagerAgentUserName = formData.value.AgentLevel=='0'?null:formData.value.AgentLevel

  if (is_add_edit.value === 'edit') {
    // formData.value.AgentStatus = is_Status.value ? "0" : '1';
    // delete formData.value.status;

    // return false
    let sql = `UPDATE agentuser SET ${sql_formart} WHERE AgentUserName = '${formData.value.AgentUserName}'; `
    console.log(sql)

    // console.log(await edit_table(sql, "userglobal"));

    const res = await edit_table(sql, 'userglobal')
    dialogVisible.value = false
    if (res && res.packageStatus === 0) {
      ElMessage({
        message: '修改成功',
        type: 'success'
      })
      setTimeout(async () => {
        await get_list('SELECT * FROM agentuser', 'userglobal')
      }, 100)
    } else {
      ElMessage({
        message: '修改失败',
        type: 'error'
      })
    }

    console.log(tableData.value)

    console.log(res)
  } else {
    console.log(formData.value)

    let arr = Object.keys(formData.value)
    let key_string = ''
    let value_string = ''
    for (var i = 0; i < arr.length; i++) {
      if (i == arr.length - 1) {
        key_string += arr[i] + ''

        if (formData.value[arr[i]] == null) {
          value_string += `${formData.value[arr[i]]}`
        } else {
          value_string += `'${formData.value[arr[i]]}'`
        }
      } else {
        key_string += arr[i] + ','
        if (formData.value[arr[i]] == null) {
          value_string += `${formData.value[arr[i]]},`
        } else {
          value_string += `'${formData.value[arr[i]]}',`
        }
      }
    }

    console.log(key_string)
    console.log(value_string)

    let sql = `INSERT INTO agentuser (${key_string}) VALUES(${value_string})`
    const res = await edit_table(sql, 'userglobal')
    console.log(res)
    dialogVisible.value = false
    if (res && res.packageStatus === 0) {
      ElMessage({
        message: '添加成功',
        type: 'success'
      })
      setTimeout(async () => {
        await get_list('SELECT * FROM agentuser', 'userglobal')
      }, 100)
    } else {
      ElMessage({
        message: '添加失败',
        type: 'error'
      })
    }
  }
}
// 开关
const switch_change = async (row) => {
  console.log(row)
  formData.value = row
  is_Status.value = row.status
  is_add_edit.value = 'edit'

  console.log(is_Status.value)

  await enter()
}

// 添加
const insert_into = () => {
  dialogVisible.value = true
  is_add_edit.value = 'add'
  formData.value = {
    AgentLevel: '', //层级
    AgentMisc: '',
    AgentNotice: '',
    AgentStatus: '', // 封禁状态
    AgentUserName: '',
    AgentUserPassword: '',
    IDCard: '',
    LoginIP: '',
    ManagerAgentUserName: '', //上级代理
    Phone: ''
  }
}

const prev_list = ref([]) //上级代理选择
// 获取列表
const get_list = async (sql, dbName) => {
  console.log(userInfo.value)
  prev_list.value = []
  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: sql,
      dbName: dbName
    }
  })
 
  let result_adta = []

  if (res.packageContent.packageMsg == '成功') {
    result_adta = []
  } else {
    let data = JSON.parse(res.packageContent.packageMsg)
    result_adta = data
    data.map((item) => {
      item['status'] = item.AgentStatus == 1 ? false : true
      console.log(item)
      if (item.AgentLevel == 0 && item.ManagerAgentUserName == '') {
        prev_list.value.push(item)
      }
    })
    // tableData.value = data;

    // console.log(del_copy(data));
    // prev_list.value = [
    //   ...del_copy(data),
    //   {
    //     AgentUserName: "最高管理",
    //     AgentLevel: "-1",
    //     ManagerAgentUserName: null,
    //     AgentMisc: "",
    //     AgentNotice: "",
    //     AgentStatus: "", // 封禁状态
    //     AgentUserPassword: "",
    //     IDCard: "",
    //     LoginIP: "",
    //     Phone: "",
    //   },
    // ];
    console.log(tableData.value)
  }
  tableData.value = result_adta

  return result_adta
}

//  去重
const del_copy = (arr) => {
  // let arr = [];
  // list.filter((item) => !arr.includes(item.AgentLevel) && arr.push(item));

  // return arr;

  let list = []
  return arr.filter((item) => !list.includes(item.AgentUserName) && list.push(item.AgentUserName))
}

// 下拉菜单
const select_change = (item) => {
  console.log(item)
  console.log(item.AgentLevel * 1 + 1 + '')

  formData.value.AgentLevel = item.AgentLevel * 1 + 1 + ''
}

// 删除
const enter_del = async (row) => {
  console.log(row)
  const res = await delete_sql(
    `DELETE FROM agentuser WHERE AgentUserName = '${row.AgentUserName}'`,
    'userglobal'
  )
  console.log(res)

  if (res && res.packageStatus === 0) {
    ElMessage({
      message: '删除成功',
      type: 'success'
    })
    setTimeout(async () => {
      await get_list('SELECT * FROM agentuser', 'userglobal')
    }, 100)
  } else {
    ElMessage({
      message: '删除失败',
      type: 'error'
    })
  }
}

// 模糊查询
const search_inp = ref('')
const search_click = async () => {
  if (search_inp.value == '') {
    await get_list(
      'SELECT * FROM agentuser ORDER BY agentuser.AgentUserName LIMIT 15 OFFSET 0',
      'userglobal'
    )
    // tableData.value = await get_list("SELECT * FROM owneruser ORDER BY owneruser.OwnerUserName LIMIT 15 OFFSET 0", "userglobal");
  } else {
  }
  await get_list(
    `SELECT * FROM agentuser WHERE AgentUserName LIKE '%${search_inp.value}%' OR Phone LIKE  '%${search_inp.value}%' OR LoginIP LIKE  '%${search_inp.value}%' OR IDCard LIKE  '%${search_inp.value}%' OR AgentNotice LIKE  '%${search_inp.value}%'`,
    'userglobal'
  )
}

// const tree_data = ref<any>([]);
// const recursion_fun = async (sql: string, dbName: string) => {
//   const res = await http.corsApi("/", "post", {
//     packID: "123456",
//     packageType: "adminSql",
//     packageContent: {
//       AgentUserName: userInfo.value.username,
//       AgentUserPassword: userInfo.value.password,
//       sql: ` SELECT * FROM agentuser WHERE(AgentLevel='${sql}')`,
//       dbName: dbName,
//     },
//   });

// };

// const get_list = async () => {
//   console.log(userInfo.value);

//   const res = await http.corsApi("/", "post", {
//     packID: "123456",
//     packageType: "adminSql",
//     packageContent: {
//       AgentUserName: userInfo.value.username,
//       AgentUserPassword: userInfo.value.password,
//       sql: "SELECT * FROM agentuser",
//       dbName: "userglobal",
//     },
//   });

//   if (res.packageContent) {
//     console.log(JSON.parse(res.packageContent.packageMsg));
//     tableData.value = JSON.parse(res.packageContent.packageMsg);
//   }

//   console.log(res);
// };
</script>

<style scoped lang="scss">
.agent {
  .title-btn {
    padding-right: 50px;
  }
}
</style>